import storage from 'good-storage'

const SEARCH_KEY ="__search__"

const SEARCH_MAX_LENGTH = 15

const PLAY_KEY = '__play__'

const PLAY_MAX_LENGTH = 200

const FAVORITE_KEY  = '__favorite__'
const FAVORITE_MAX_LEN = 200


function insertArray (arr,val,compare,maxLen) {
    const index = arr.findIndex(compare)

    if(index===0) {
        return;
    }
    if(index>0) {
        arr.splice(index,1)
    }
    arr.unshift(val);

    if(maxLen && arr.length >maxLen) {
        arr.pop();
    }
}

function deleteFormArray(arr,compare) {
    const index =arr.findIndex(compare)
    if(index>-1){
        arr.splice(index,1)
    }
}


//存搜索历史到localstorage
export function saveSearch (query) {
    let searches = storage.get(SEARCH_KEY,[])
    insertArray(searches,query,(item)=>{
         return item === query
    },SEARCH_MAX_LENGTH)
    storage.set(SEARCH_KEY,searches)
    return searches;
}


//从localstorage读取搜索历史
export function loadSearch() {
    return storage.get(SEARCH_KEY,[])
}

// 删除搜索历史
export function deleteSearch (query) {
    let searches =storage.get(SEARCH_KEY,[])

    deleteFormArray(searches,(item)=>{
        return item===query
    })

    storage.set(SEARCH_KEY,searches)
    return searches;
}


export function clearAllSearch () {
    storage.remove(SEARCH_KEY)
    return []
}


//保存播放历史
export function savePlay(song) {
    let songs=storage.get(PLAY_KEY,[]);
    insertArray(songs,song,(item)=>{
        return item.id===song.id
    },PLAY_MAX_LENGTH)
    storage.set(PLAY_KEY,songs)
    return songs;
}

// 从本地缓存拿出播放历史
export function loadPlay() {
    return storage.get(PLAY_KEY,[])
}

//----- 收藏歌曲的列表


// 保存收藏歌曲的列表
export function saveFavorite(song) {
    let songs = storage.get(FAVORITE_KEY,[])
    insertArray(songs,song,(item)=>{
        return song.id===item.id
    },FAVORITE_MAX_LEN)
    storage.set(FAVORITE_KEY,songs)
    return songs;
}


// 删除收藏歌曲
export function deleteFavorite(song) {
    let songs = storage.get(FAVORITE_KEY,[])
    deleteFormArray(songs,(item)=>{
        return song.id===item.id
    })
    storage.set(FAVORITE_KEY,songs)
    return songs;
}


export function loadFavorite() {
    console.log('load __favorite__')
    return storage.get(FAVORITE_KEY,[])
}